<template>
  <view class="container">
    <!-- 使用自定义的搜索组件 -->
    <view class="search-box">
      <my-search @click="gotoSearch"></my-search>
    </view>

    <view class="tag-box">
      <!-- 添加可左右滑动的标签栏 -->
      <scroll-view class="scroll-view_H" scroll-x="true">
        <view
          class="scroll-view-item_H"
          v-for="(tag, index) in tags"
          :key="index"
          :class="{ active: activeTagIndex === index }"
          @click="selectTag(index)"
        >
          {{ tag }}
        </view>
      </scroll-view>
      <view class="list-icon" @click="toggleMenu">
        <image src="/static/my-icons/filter.png" mode="aspectFit" />
      </view>
    </view>
    <view class="my_color">
      <view class="content">
        <!-- 组团信息列表显示区域 -->
        <view v-if="groupList.length > 0">
          <view
            v-for="(group, groupIndex) in groupList"
            :key="groupIndex"
            class="group-item"
            @click="getGroupDetail(group.tuanId)"
          >
            <view class="top-box">
              <image :src="group.avatar" class="avatar"></image>
              <view class="top-a">
                <view class="nickname">{{ group.name }}</view>
                <view class="send_time">{{ group.sendTime }}</view>
              </view>
            </view>
            <text class="tuan-title">
              {{
                group.expanded
                  ? group.tuanTitle
                  : group.tuanTitle.slice(0, 20) +
                    (group.tuanTitle.length > 20 ? "..." : "")
              }}
            </text>
            <br />

            <text class="tuan-detail">
              {{
                group.expanded
                  ? group.tuanDetail
                  : group.tuanDetail.slice(0, 80) +
                    (group.tuanDetail.length > 80 ? "..." : "")
              }}
            </text>
            <text v-if="group.tuanDetail.length > 80" class="toggle-btn"
              >详情</text
            >
            <!-- 添加 threeImages 显示 -->
            <view class="three-images">
              <image
                v-for="(image, imgIndex) in group.threeImages"
                :key="imgIndex"
                :src="image"
                class="theImage"
              ></image>
            </view>
          </view>
        </view>
        <view v-else class="no-content"> 暂无内容~ </view>
      </view>
    </view>
    <!-- 添加滚动加载提示 -->
    <view v-if="loadingMore" class="loading-more">加载中...</view>
    <!-- 弹出菜单 -->
    <view class="menu" v-if="showMenu">
      <view class="menu-item" @click="editTags">编辑标签</view>
      <view class="menu-item" @click="filterByDistance">距离筛选</view>
      <view class="menu-item" @click="filterByTime">时间筛选</view>
    </view>
    <!-- 弹出框 -->
    <uni-popup ref="distancePopup" type="dialog">
      <uni-popup-dialog
        type="info"
        title="距离筛选"
        :before-close="true"
        @confirm="applyDistanceFilter"
        @close="cancelDistanceFilter"
      >
        <view class="filter-container">
          <view class="switch-container">
            <view class="label">启用距离筛选</view>
            <switch
              :checked="distanceFilterEnabled"
              @change="toggleDistanceFilter"
            />
          </view>
          <view class="input-container" v-if="distanceFilterEnabled">
            <input
              type="number"
              v-model="distanceValue"
              placeholder="请输入距离"
              @input="updateDistanceValue"
            />
            <view class="unit">km</view>
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
    <!-- 时间筛选弹出框 -->
    <uni-popup ref="timePopup" type="dialog">
      <uni-popup-dialog
        type="info"
        title="时间筛选"
        :before-close="true"
        @confirm="applyTimeFilter"
        @close="cancelTimeFilter"
      >
        <view class="filter-container">
          <view class="switch-container">
            <view class="label">启用时间筛选</view>
            <switch :checked="timeFilterEnabled" @change="toggleTimeFilter" />
          </view>
          <view class="input-container2" v-if="timeFilterEnabled">
            <view class="twoTime">
              <uni-datetime-picker
                placeholder="选择开始时间"
                type="datetime"
                :value="timeFilterValues.startTime"
                @change="handleStartTimeChange"
              />
            </view>
            <view class="twoTime">
              <uni-datetime-picker
                placeholder="选择结束时间"
                type="datetime"
                :value="timeFilterValues.endTime"
                @change="handleEndTimeChange"
              />
            </view>
          </view>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tags: [
        "推荐",
        "学习",
        "游戏",
        "运动",
        "旅游",
        "吃喝",
        "玩乐",
        "拼团",
        "摄影",
      ],
      activeTagIndex: 0, // 添加 activeTagIndex 属性
      groupList: [],
      tuanUserId: "",
      name: "",
      avatar: "",
      threeImages: "",
      tuanId: "",
      tuanTitle: "",
      tuanDetail: "",
      sendTime: "",
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页大小
      loadingMore: false, // 是否正在加载更多
      showMenu: false, // 控制弹出菜单的显示和隐藏
      showDistanceFilter: false, // 控制距离筛选弹出框的显示和隐藏
      distanceFilterEnabled: false, // 控制距离筛选开关的状态
      distanceValue: "", // 存储输入的距离值
      originalDistanceFilterEnabled: false, // 保存原始的距离筛选开关状态
      originalDistanceValue: "", // 保存原始的距离值
      timeFilterEnabled: false, // 控制时间筛选开关的状态
      timeFilterValues: { startTime: "", endTime: "" }, // 修改属性名
      originalTimeFilterEnabled: false, // 保存原始的时间筛选开关状态
      originalTimeFilterValues: { startTime: "", endTime: "" }, // 保存原始的时间值
    };
  },

  onShow() {
    if (!uni.getStorageSync("userTags")) {
      this.getUserTag();
    }
  },
  onLoad() {
    this.groupListVo();
  },

  methods: {
    //获取用户首页标签
    getUserTag() {
      const userId = uni.getStorageSync("userId");
      uni.$http
        .get(`/tag/getUserTag?userId=${userId}`)
        .then((res) => {
          if (res.data.code === 200) {
            console.log("获取用户标签成功:", res.data.data);
            this.tags = res.data.data;
            uni.setStorageSync("userTags", this.tags);
          } else {
            console.log("获取用户标签失败:", res.data.data.message);
          }
        })
        .catch((err) => {
          console.error("获取用户标签失败:", err);
        });
    },
    // 获取组团信息列表
    groupListVo() {
      const userId = uni.getStorageSync("userId");
      console.log("--------userId:", userId);
      const activeTag = this.tags[this.activeTagIndex]; // 获取选中的标签
      const requestData = {
        userId: userId,
        selectedTag: activeTag,
        page: this.currentPage,
        pageSize: this.pageSize,
        distanceValue: this.distanceValue,
        startTime: this.timeFilterValues.startTime,
        endTime: this.timeFilterValues.endTime,
      };
      uni.$http
        .post(`/tuan/getGroupList`, requestData) // 将选中的标签、页码和每页大小作为请求体传递
        .then((res) => {
          console.log("主页获取组团信息", res.data);
          // 解析服务器返回的 JSON 数据
          const responseData = res.data;
          if (responseData.code === 200) {
            this.groupList = this.groupList.concat(
              responseData.data.map((group) => ({
                ...group,
                expanded: false, // 默认不展开
              }))
            );
            this.loadingMore = false; // 加载完成
          } else {
            console.log("主页获取组团信息失败:", responseData.message);
            this.loadingMore = false; // 加载完成
          }
        })
        .catch((err) => {
          console.error("主页获取组团信息失败:", err);
          this.loadingMore = false; // 加载完成
        });
    },

    //搜索
    gotoSearch() {
      uni.navigateTo({
        url: "/subpkg/search/search",
      });
    },

    //选中标签
    selectTag(index) {
      // 添加 selectTag 方法
      this.activeTagIndex = index;
      this.groupList = []; // 清空上次获得的数据
      this.currentPage = 1; // 重置页码
      this.groupListVo(); // 切换标签时重新获取组团信息
    },

    // 获取组团详情
    getGroupDetail(tuanId) {
      uni.navigateTo({
        url: `/subpkg/group_detail/group_detail?tuanId=${tuanId}`,
      });
    },

    // 加载更多数据
    loadMore() {
      if (this.loadingMore) return; // 如果已经在加载中，则不重复加载
      this.loadingMore = true; // 标记为正在加载
      this.currentPage++; // 增加页码
      this.groupListVo(); // 获取更多数据
    },

    // 切换弹出菜单的显示和隐藏
    toggleMenu() {
      this.showMenu = !this.showMenu;
    },

    // 编辑标签
    editTags() {
      console.log("编辑标签");
      // 添加编辑标签的逻辑
      uni.navigateTo({
        url: `/subpkg/edit_tags/edit_tags?tags=${this.tags}`,
      });
      this.showMenu = false; // 关闭菜单
    },

    // 距离筛选
    filterByDistance() {
      console.log("距离筛选");
      this.originalDistanceFilterEnabled = this.distanceFilterEnabled; // 保存原始的距离筛选开关状态
      this.originalDistanceValue = this.distanceValue; // 保存原始的距离值
      this.$refs.distancePopup.open(); // 使用 uni-popup 打开弹出框
      this.showMenu = false; // 关闭菜单
    },
    toggleDistanceFilter() {
      this.distanceFilterEnabled = !this.distanceFilterEnabled; // 切换开关状态
      if (!this.distanceFilterEnabled) {
        this.distanceValue = "";
      }
    },
    updateDistanceValue(event) {
      // 检查 event.detail 是否存在
      if (event && event.detail) {
        this.distanceValue = event.detail.value; // 更新输入的距离值
      }
    },

    applyDistanceFilter() {
      if (
        this.distanceFilterEnabled &&
        (!this.distanceValue || this.distanceValue.trim() === "")
      ) {
        uni.showToast({
          title: "请输入距离",
          icon: "none",
        });
      } else {
        console.log("应用距离筛选", this.distanceValue);
        // 在这里添加应用距离筛选的逻辑
        this.$refs.distancePopup.close(); // 关闭弹出框
        this.groupList = [];
        this.groupListVo();
      }
    },
    cancelDistanceFilter() {
      console.log("取消距离筛选");
      this.distanceFilterEnabled = this.originalDistanceFilterEnabled; // 恢复原始的距离筛选开关状态
      this.distanceValue = this.originalDistanceValue; // 恢复原始的距离值
      this.$refs.distancePopup.close(); // 关闭弹出框
    },

    // 时间筛选
    filterByTime() {
      console.log("时间筛选");
      this.originalTimeFilterEnabled = this.timeFilterEnabled; // 保存原始的时间筛选开关状态
      this.originalTimeFilterValues = { ...this.timeFilterValues }; // 保存原始的时间值
      this.$refs.timePopup.open(); // 使用 uni-popup 打开弹出框
      this.showMenu = false; // 关闭菜单
    },
    toggleTimeFilter() {
      this.timeFilterEnabled = !this.timeFilterEnabled; // 切换开关状态
      if (!this.timeFilterEnabled) {
        this.timeFilterValues = { startTime: "", endTime: "" }; // 修改属性名
      }
    },
    applyTimeFilter() {
      if (
        this.timeFilterEnabled &&
        (!this.timeFilterValues.startTime || !this.timeFilterValues.endTime)
      ) {
        uni.showToast({
          title: "请选择开始时间和结束时间",
          icon: "none",
        });
      } else {
        console.log("应用时间筛选", this.timeFilterValues);
        // 在这里添加应用时间筛选的逻辑
        this.$refs.timePopup.close(); // 关闭弹出框
        this.groupList = [];
        this.groupListVo();
      }
    },
    cancelTimeFilter() {
      console.log("取消时间筛选");
      this.timeFilterEnabled = this.originalTimeFilterEnabled; // 恢复原始的时间筛选开关状态
      this.timeFilterValues = { ...this.originalTimeFilterValues }; // 恢复原始的时间值
      this.$refs.timePopup.close(); // 关闭弹出框
    },
    handleStartTimeChange(e) {
      console.log("Start date change event:", e); // 调试信息
      this.timeFilterValues.startTime = e; // 直接使用 e
    },
    handleEndTimeChange(e) {
      console.log("End date change event:", e); // 调试信息
      this.timeFilterValues.endTime = e; // 直接使用 e
    },
  },

  // 监听滚动事件
  onReachBottom() {
    this.loadMore(); // 滚动到底部时加载更多数据
  },
};
</script>

<style lang="scss">
.container {
  display: flex;
  flex-direction: column;
  position: relative; // 添加相对定位
}
.my_color {
  width: 100%;
  height: 150px; /* 设置view的总高度 */
  position: relative;
  background: linear-gradient(
    to bottom,
    rgb(244, 227, 184),
    rgb(245, 245, 245)
  );
}

.group-item {
  background-color: white;
  padding: 2vw;
  margin-bottom: 1.8vw;
  margin-left: 1.8vw;
  margin-right: 1.8vw;
  border-radius: 13px;

  .top-box {
    margin-top: 1px;
    height: 44px;
    width: 205px;
    display: flex;
    position: relative;
  }

  .avatar {
    display: block;
    width: 32px;
    height: 32px;
    border-radius: 50%;
  }

  .top-a {
    display: flex;
    flex-direction: column;
    padding-left: 10px;

    .nickname {
      color: #1d1c1c;
      font-size: 13px;
      max-width: 130px; /* 设置最大宽度 */
      white-space: nowrap; /* 防止换行 */
      overflow: hidden; /* 隐藏溢出内容 */
      text-overflow: ellipsis; /* 省略号显示 */
    }

    .send_time {
      color: #6a6666;
      font-size: 11px;
      margin-top: 2px;
    }
  }
}

.search-box {
  // 设置定位效果为“吸顶”
  position: sticky;
  // 吸顶的“位置”
  top: 0;
  // 提高层级，防止被轮播图覆盖
  z-index: 999;
}

/* 标签栏样式 */
.scroll-view_H {
  white-space: nowrap;
  width: 90%;
  background: linear-gradient(
    to bottom,
    rgb(251, 210, 105),
    rgb(244, 227, 184)
  );
}

.scroll-view-item_H {
  display: inline-block;
  height: 25px; // 修改高度
  line-height: 25px; // 修改行高
  text-align: center;
  font-size: 14px; // 修改字体大小
  margin-right: 2px;
  padding: 0 10px; // 添加内边距以适应文字
}

// 添加 active 类的样式
.scroll-view-item_H.active {
  font-size: 17px;
}

.no-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 170px;
  color: #6d6d6d;
}

.tuan-title {
  font-weight: bold;
}

.tuanDetail {
  display: flex;
}

.toggle-btn {
  color: #1983f4;
  font-size: 16px;
  cursor: pointer;
  margin-top: 5px;
}

//  添加 threeImages 样式
.three-images {
  display: flex;
  margin-top: 10px;
}

.theImage {
  width: 29vw;
  height: 29vw;
  margin-right: 1vw;
  border-radius: 10px;
}

// 添加加载更多提示样式
.loading-more {
  text-align: center;
  padding: 10px;
  color: #6a6666;
}

.tag-box {
  display: flex;
}

.list-icon {
  width: 10%;
  height: auto;
  background: linear-gradient(
    to bottom,
    rgb(251, 210, 105),
    rgb(244, 227, 184)
  );

  image {
    width: 100%;
    height: 100%;
  }
}

.menu {
  position: absolute;
  top: 70px; // 根据需要调整位置
  right: 10px; // 根据需要调整位置
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.menu-item {
  padding: 10px 20px;
  cursor: pointer;
}

.menu-item:hover {
  background-color: #f0f0f0;
}
.switch-container {
  display: flex;
  align-items: center;
  .label {
    margin-right: 3px;
  }
}
.input-container {
  padding-top: 5px;
  display: flex;
  align-items: center;
  input {
    padding: 5px;
    margin-right: 3px;
    border: 1px solid #ececec;
    border-radius: 5px;
    width: 70%;
    background-color: #f7f7f7;
  }
}
.input-container2 {
  padding-top: 5px;
  align-items: center;
  width: 100%;
}
.picker {
  padding: 5px;
  margin-right: 3px;
  border: 1px solid #ececec;
  border-radius: 5px;
  width: 70%;
  background-color: #f7f7f7;
}
.twoTime {
  display: flex;
  width: 100%;
  align-items: center;
  margin-bottom: 4px;
}
</style>